﻿namespace CloudNinja.Metering.Providers.Configuration.IISLog
{
    using System.Configuration;

    using CloudNinja.Metering.Common;
    using CloudNinja.Metering.Common.Configuration;
    using CloudNinja.Metering.Common.Logging;
    using CloudNinja.Metering.Data;
    using CloudNinja.Metering.Providers;
    using CloudNinja.Metering.Providers.WebRole;

    using Microsoft.Practices.Unity;

    public sealed class IISLogMeteringProviderElement : ProviderElement
    {
        [ConfigurationProperty("IISLogMeteringProviderSettings")]
        public IISLogMeteringProviderSettings ProviderSettings
        {
            get
            {
                return (IISLogMeteringProviderSettings)this["IISLogMeteringProviderSettings"];
            }

            set
            {
                this["IISLogMeteringProviderSettings"] = value;
            }
        }

        public override void RegisterType(IUnityContainer container, MeteringSection meteringConfiguration)
        {
            if (!container.IsRegistered(typeof(IParserBookmarkRepository)))
            {
                var azureStorageLogParsingStateRepositoryCtor =
                    new InjectionConstructor(
                        this.ProviderSettings.IISLogsParserBookmarkRepository, container.Resolve<ILogger>());
                container.RegisterType<IParserBookmarkRepository, AzureStorageParserBookmarkRepository>(
                    new ContainerControlledLifetimeManager(), azureStorageLogParsingStateRepositoryCtor);
            }

            var iisLogProviderInjectionCtor = new InjectionConstructor(
                this.CollectInterval,
                this.ProviderSettings.IISLogsRepositoryConnStr,
                this.ProviderSettings.TenantIdentifierLocation,
                this.ProviderSettings.TenantIdentifierPattern,
                container.Resolve<ILogger>(),
                container.Resolve<IParserBookmarkRepository>(),
                container.Resolve<IMeteringRepository>(),
                container.Resolve<IMeteringContext>());

            container.RegisterType<IMeteringProvider, IISLogProvider>(typeof(IISLogProvider).ToString(), new ContainerControlledLifetimeManager(), iisLogProviderInjectionCtor);
        }

        protected override object OnRequiredPropertyNotFound(string name)
        {
            // HACK: Do not really understand why it comes here with these properties, which is clearly defined above.
            return name.Equals("Name") || name.Equals("CollectInterval") ? null : base.OnRequiredPropertyNotFound(name);
        }
    }
}